package com.atguigu.tingshu.order.pattern;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.pattern.strategy.TradeOrderStrategy;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 策略模式抽象类：封装复用代码
 * @author: atguigu
 * @create: 2025-03-25 16:22
 */
public abstract class AbstractTradeOrderStrategy implements TradeOrderStrategy {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 为本次订单结算生成流水号
     * @param orderInfoVo
     */
    protected void generateTradeNo(OrderInfoVo orderInfoVo) {
        Long userId = AuthContextHolder.getUserId();
        String tradeNo = IdUtil.randomUUID();
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        redisTemplate.opsForValue().set(tradeKey, tradeNo, RedisConstant.ORDER_TRADE_EXPIRE, TimeUnit.MINUTES);
        orderInfoVo.setTradeNo(tradeNo);
    }


    /**
     * 为本次订单生成签名值
     * @param orderInfoVo
     */
    protected void generateSign(OrderInfoVo orderInfoVo) {
        orderInfoVo.setTimestamp(System.currentTimeMillis());
        //将订单VO转为Map TODO：VO中包含付款方式"payWay"此时为空 生成签名将排除掉payWay字段，故暂时不参与签名
        Map<String, Object> map = BeanUtil.beanToMap(orderInfoVo, false, true);
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign);
    }



}
